/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.registry.Registry;
import java.util.HashMap;
import java.util.Map;

import jp.aist.gtrc.plus.reserve.ReserveException;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.util.AppOption;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;

import org.apache.log4j.Logger;


public class SchedulerOptions extends AppOption {

	private static final String OPT_SCHED_TGT = "-t";
	private static final String OPT_SCHED_ALGO = "-a";
	private static final String OPT_SCHED_CONFFILE = "-c";
	private static final String OPT_SCHED_RSVPATH = "-r";
	private static final String OPT_RMI_PORT = "-rp";
	private static final String OPT_SCHED_MAX_EXPIRED = "-ne";
	private static final String OPT_SCHED_SGE_QNAME = "-sgeq";

	public static final String DEFAULT_SCHED_RSVPATH = "/usr/local/PluS";
	private static final String DEFAULT_SCHED_MAX_EXPIRED = "10";
	private static final String APP_NAME = "plus_scheduler";

	private Map<String, String> confs;
	private static final SchedulerOptions instance;
	private static final String DELIM_TITLE = "\\s*:\\s*";
	protected static final Logger logger = Logger.getLogger(SchedulerOptions.class);

	static {

		instance = new SchedulerOptions();

	}

	protected SchedulerOptions(){

		super(APP_NAME);
		addOption(OPT_SCHED_TGT, "target", "target grid system (sge, sgesched, pbs, pbsdyn, condor)", "sge");
		addOption(OPT_SCHED_ALGO, "algo", "scheduling algolithm (Fifo, Sort)", "Sort");
		addOption(OPT_SCHED_CONFFILE, "conffile", "scheduler config file", "");
		addOption(OPT_SCHED_RSVPATH, "rsvFPath", "reserve db file path",
				DEFAULT_SCHED_RSVPATH);
		addOption(OPT_RMI_PORT, "rmiPort", "RMI registry port",
				Integer.toString(Registry.REGISTRY_PORT));
		addOption(OPT_SCHED_MAX_EXPIRED, "maxExp",
				"max # of expired reserves to be remained (-1: never remove)",
				DEFAULT_SCHED_MAX_EXPIRED);
		addOption(OPT_SCHED_SGE_QNAME, "qNames",
				"default SGE queue names to restrict reserve nodes "
				+ "within nodes on them (A.q{,B.q,...})", null);

	}

	static SchedulerOptions getInstance() {

		return instance;

	}

	public String getTargetSystem(){

		return getOptionValue(OPT_SCHED_TGT);

	}
	public String getSchedAlgolithm(){

		return getOptionValue(OPT_SCHED_ALGO);

	}

	public String getSchedConfigFile(){

		return getOptionValue(OPT_SCHED_CONFFILE);

	}

	public String getReserveFilePath(){

		return getOptionValue(OPT_SCHED_RSVPATH);

	}

	public int getRMIPort() throws ReserveException {

		String p = getOptionValue(OPT_RMI_PORT);
		try {
			return Integer.parseInt(p);
		} catch (NumberFormatException e) {
			throw new ReserveException("invalid RMI port num: " + p);
		}

	}

	public int getMaxExpiredReserves() throws ReserveException {

		try {
			int n = Integer.parseInt(getOptionValue(OPT_SCHED_MAX_EXPIRED));
			return (n >= 0) ? n : Integer.MAX_VALUE;
		} catch (NumberFormatException e) {
			throw new ReserveException(OPT_SCHED_MAX_EXPIRED + " needs integer");
		}

	}

	public String getSGEQueueName() {

		return getOptionValue(OPT_SCHED_SGE_QNAME);

	}

	private void readConfig(String conffile) throws SchedulerException {

		if (TextUtil.isEmpty(conffile)){
			// if conffile is not specified, do nothing, not throw Exception
			return;
		}

		/*
		 * Read scheduler config file
		 */
		BufferedReader in;
		try {
			in = new BufferedReader(new FileReader(conffile));
		} catch (FileNotFoundException e) {
			logger.fatal("cannot open config file: " + conffile);
			throw new SchedulerException("cannot open config file: " + conffile);
		}
		logger.info("open config file: " + conffile);

		try {
			confs = new HashMap<String, String>();
			while (true){
				String line = in.readLine();
				if (line == null) {
					// reached EOF
					break;
				}
				if (line.matches("\\s*|\\s*#.*")) {
					// empty or comment line
					continue;
				}

				String[] s = line.split(DELIM_TITLE);
				if (s.length != 2) {
					logger.warn("invalid config statement, ignored: " + line);
					continue;
				}
				if (confs.containsKey(s[0])) {
					logger.warn("Duplicate " + s[0] + ", refers first one");
					continue;
				}
				confs.put(s[0], s[1]);
			}
		} catch (IOException e) {
			logger.error("read config file failed: " + conffile);
			throw new SchedulerException("read config file failed: " + conffile);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// ignore
			}
		}

	}

	public Map<String, String> getConfig() throws SchedulerException {

		if (confs != null) {
			return confs;
		} else {
			readConfig(getSchedConfigFile());
			return confs;
		}

	}

}
